﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Reflection;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class _Default : System.Web.UI.Page
{
    // TODO: VAD SKA VI LOGGA?

    #region Variables

    private Validation validation;
    private const string loggedInSession = "LoggedIn";
    private const string redirectPage = "~/Forum.aspx";

    #endregion


    protected void Page_Load(object sender, EventArgs e)
    {
        validation = new Validation();
        if (Session["UserAgent"] != null)
        {
            Response.Write(Session["Useragent"]);
        }
    }


    protected void LoginButton_Click(object sender, EventArgs e)
    {
        string username = Username.Value.ToString();
        string password = Password.Value.ToString();
        Service service = new Service();
        if (validation.LoginValidation(username, password))
        {
            Login(username, password);
        }
        else
        {

            LoggEntry loggEntry = new LoggEntry();
            loggEntry.Details = String.Format("User : {0}, Has failed to login", username);
            loggEntry.IP = Request.UserHostAddress;
            service.SaveLoggEntry(loggEntry);

            List<string> errormessages = validation.GetErrorMessages();

            if (errormessages != null)
            {
                foreach (string error in errormessages)
                {
                    AddErrorMessage(error);
                }
            }
        }
    }




    private void Login(string suppliedUsername, string suppliedPassword)
    {
        Session.Contents.RemoveAll();

        Service service = new Service();
        UserCredentials uc = service.GetUserCredentialsOnUsername(suppliedUsername);
        Hashing hashing = new Hashing();

        if (uc == null)
        {
            AddErrorMessage("Wrong Username And/Or Password");
            LoggEntry loggEntry = new LoggEntry();
            loggEntry.Details = String.Format("User : {0}, Has failed to login", suppliedUsername);
            loggEntry.IP = Request.UserHostAddress;
            service.SaveLoggEntry(loggEntry);

        }
        else if (uc != null)
        {
            if (uc.Password == hashing.HashPassword(suppliedPassword, uc.Salt))
            {
                Session["UserAgent"] = Request.UserAgent.ToString();
                Session["User"] = uc;
                Response.Redirect(redirectPage);
            }
            AddErrorMessage("Wrong username and / or password.");
            LoggEntry loggEntry = new LoggEntry();
            loggEntry.Details = String.Format("User : {0}, Has failed to login", suppliedUsername);
            loggEntry.IP = Request.UserHostAddress;
            service.SaveLoggEntry(loggEntry);
        }
        else
        {
            AddErrorMessage("Wrong username and / or password.");
            LoggEntry loggEntry = new LoggEntry();
            loggEntry.Details = String.Format("User : {0}, Has failed to login", suppliedUsername);
            loggEntry.IP = Request.UserHostAddress;
            service.SaveLoggEntry(loggEntry);

        }

    }

    #region  AddErrorMessage

    private void AddErrorMessage(string message)
    {
        Validators.Add(new CustomValidator
        {
            ErrorMessage = message,
            IsValid = false
        });
    }

    private void AddErrorMessage(IDataErrorInfo obj)
    {
        obj.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public)
            .Select(p => p.Name)
            .Where(n => !String.IsNullOrWhiteSpace(obj[n])) // vill bara ha de som inte är tomma.
            .ToList()  // gör om till lista.
            .ForEach(n => AddErrorMessage(obj[n]));  // loopar igenom namnen som återstår o lägger till.
    }

    #endregion


}